<?php
// +----------------------------------------------------------------------
// | yogurt
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Author: fengyi <1719847255.qq.com>
// +----------------------------------------------------------------------

namespace yogurt;

use yogurt\validate\ValidateRule;

/**
 * Class Validate
 * @package yogurt
 */
class Validate
{

    protected $rule = [];
    protected $data = [];
    protected $message = [];
    protected static $error = '';


    public function __construct($data = [])
    {
        $this->data = array_merge($data, $this->data);
    }

    /**
     *  验证方法
     * @param $data
     * @return bool
     */
    public function check($data): bool
    {
        foreach ($this->rule as $key => $value) {
            if (is_numeric($value)) {
                if (!static::equals($key, $data[$key] ?? $key, $value, $this->message)) {
                    return false;
                }
            }
            $methods = explode('|', $value);
            foreach ($methods as $vms) {
                if (is_numeric($vms)) {
                    if (!static::equals($key, $data[$key] ?? $key, $vms, $this->message)) {
                        return false;
                    }
                }
                $vm = explode(':', $vms);
                $method = $vm[0];
                if (method_exists($this, $method)) {

                    $return = $this->$method($key, $data[$key] ?? $key, $vm, $this->message);
                    if ($return !== true) {
                        static::$error = $return;
                        return false;
                    }
                }
                if (!static::$method($key, $data[$key] ?? $key, $vm, $this->message)) {
                    return false;
                }
            }
        }
        return true;
    }


    /**
     *  设置验证提示
     * @param $name
     * @param $value
     * @return void
     */
    public function setError($name, $value)
    {
        $this->$name = $value;
    }

    /**
     *  获取验证提示
     * @return string
     */
    public function getError(): string
    {
        return static::$error;
    }


    /**
     * 静态类调用入口
     * @param $method
     * @param $args
     * @return bool
     */
    public static function __callStatic($method, $args)
    {
        $validateRule = new ValidateRule();
        if (method_exists($validateRule, $method)) {
            if (!$validateRule->$method($args)) {
                static::$error = $validateRule->errorMsg;
                return false;
            }
        }
        return true;
    }

    public function __set($name, $value)
    {
        $this->setError($name, $value);
    }

    public function __get($key)
    {
        return $key;
    }

    private function __clone()
    {
    }
}
